import json
import logging
import re
import matplotlib.pyplot as plt
import time

import pandas as pd

# 设置全局字体
plt.rcParams['font.family'] = 'FangSong'

logging.basicConfig(format='%(asctime)s -- %(name)s -- %(funcName)s -- %(levelname)s -- %(message)s',
                    level=logging.INFO)
LOGGER = logging.getLogger(__name__)

# 添加一个FileHandler来保存日志到文件
file_handler = logging.FileHandler('my_log.log', encoding='utf-8')
file_handler.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s -- %(name)s - %(funcName)s -- %(levelname)s -- %(message)s')
file_handler.setFormatter(formatter)
LOGGER.addHandler(file_handler)


def custom_logger(string1, string2):
    # 获取当前模块名和函数名
    module_name = __name__
    function_name = custom_logger.__name__

    # 记录日志
    LOGGER.info(f"{string1} -- {string2}")


def custom_logger(string1, string2):
    # 记录日志
    LOGGER.info(f"{string1} -- {string2}")


def generate_group_graph(dataframe):
    # todo 勉强可以使用
    # 剔除role值为'boss'的数据
    filtered_df = dataframe[dataframe['role'] != 'boss']

    # 按name进行分组
    groups = filtered_df.groupby('name_people')

    # 计算图像大小
    num_groups = len(groups)
    fig_height = num_groups * 1  # 每个group占用1.5个单位的高度

    # 创建图形
    fig, ax = plt.subplots(figsize=(8, fig_height))

    # 生成每个group的图像块
    current_height = fig_height  # 初始高度
    for i, (name, group) in enumerate(groups):
        task_names = group['name_task'].tolist()
        task_bonus = group['bonus_task'].tolist()
        task_cost = group['cost'].tolist()

        # 绘制便签
        ax.text(0, current_height, name, fontsize=30, weight='bold')

        # 绘制任务名称
        for j, task_name in enumerate(task_names):
            ax.text(0.7, current_height - j * 0.5, task_name, fontsize=20, weight='bold')
            ax.text(1.5, current_height - j * 0.5, f"奖励:{task_bonus[j]};消耗{task_cost[j]}", fontsize=18,
                    weight='bold', color='blue')

        # 更新当前高度
        current_height -= (len(task_names) * 0.5 + 0.5)  # 每个任务名称占用0.5个单位的高度，加上0.5个单位的间距


    # 设置图形样式和布局
    ax.set_xlim(0, 2)
    ax.set_ylim(0, fig_height)
    ax.set_facecolor('black')
    ax.axis('off')

    # 生成图像文件名
    timestamp = time.strftime('%Y%m%d%H%M%S', time.localtime())
    filename = f'temp/graph_{timestamp}.png'

    # 保存图像文件
    plt.savefig(filename)

    # 返回图像文件路径
    return filename


def calculate_penalty(df):
    # 找到最大的项目时间
    project_real_duration = person_duration.max()
    # 计算惩罚系数
    penalty = df['duration'].values[0] / project_real_duration
    penalty = penalty if penalty < 1 else 1
    df['penalty'] = penalty
    df['project_real_duration'] = project_real_duration
    return penalty, df


def calculate_earnings(penalty, df):
    # 计算工资收益
    df['salary_earnings'] = df['salary'] * df['project_real_duration'] / 30
    df['salary_earnings'] = df['salary_earnings'].astype(int)
    # 计算任务收益
    person_bonus = df.groupby('name_people')['bonus_task'].sum()
    task_earnings = person_bonus * penalty
    return task_earnings


def calculate_physical_penalty(penalty, df, people):
    # 计算每个人名下的所有task的cost之和
    person_cost = df.groupby('name_people')['cost'].sum()
    # 计算体力惩罚
    people['physical_penalty'] = person_cost - people['energy']
    people.loc[people['physical_penalty'] <= 0, 'physical_penalty'] = 0
    people['physical_penalty'] *= penalty  # 体力惩罚系数
    return df


def calculate_cash_retention(df):
    # 计算现金留存
    df['cash_retention'] = df['cash'] + df['earnings'] - df['rent_expense'] - df['living_expense'] - df[
        'social_expense'] - df['energy'] * 0.1
    return df


def extract_json_code_blocks(markdown_text):
    # 定义正则表达式模式
    pattern = r"```json\s+(.*?)\s+```"

    # 提取代码块中的JSON数据
    json_blocks = re.findall(pattern, markdown_text, re.DOTALL)

    if json_blocks:
        return json.loads(json_blocks[0])
    else:
        return {}


def test_generate_group():
    data = {
        'name_people': ['John', 'John', 'ann', 'Alice', 'Alice', 'Bob', 'Bob', 'Bob', 'Jerry', 'kind'],
        'task_name': ['Task 1', 'Task 2', 'Task 3', 'Task 4', 'Task 5', 'Task 6', 'Task 7', 'Task 8', 'Task 9',
                      'Task 10'],
        'bonus_task': [100, 100, 100, 100, 200, 200, 3200, 200, 200, 300],
        'cost': [100, 100, 100, 100, 200, 200, 3200, 200, 200, 300]
    }
    df = pd.DataFrame(data)
    graph_path = generate_group_graph(df)
    print(graph_path)


def text_test():
    text_test = """
        ```json
{
    "is_change_relationship": true,
    "new_relationship": "喜欢",
    "reason": "在这个对话中，迪丽热巴向杨幂介绍了一个有趣且重要的项目，并以友好和鼓励的方式表达了对杨幂的认可和信任。这种积极的互动有助于改善她们之间的关系，并使杨幂感到受到尊重和重视。因此，我认为这种对话可以改变她们之间的关系，使她们更加喜欢对方。"
}
```
        """
    print(extract_json_code_blocks(text_test))


if __name__ == '__main__':
    # 使用自定义logger记录日志
    # test_generate_group()
    # 示例数据
    data = {
        'name_people': ['John', 'John', 'ann', 'Alice', 'Alice', 'Bob', 'Bob', 'Bob', 'Jerry', 'kind'],
        'name_task': ['Task 1', 'Task 2', 'Task 3', 'Task 4', 'Task 5', 'Task 6', 'Task 7', 'Task 8', 'Task 9',
                      'Task 10'],
        'role': ['worker', 'worker', 'worker', 'worker', 'boss', 'worker', 'worker', 'worker', 'worker', 'worker'],
        'bonus_task': [100, 100, 100, 100, 200, 200, 3200, 200, 200, 300],
        'cost': [100, 100, 100, 100, 200, 200, 3200, 200, 200, 300]
    }

    # 转换为DataFrame
    df = pd.DataFrame(data)

    # 生成任务图表并返回图像的存储路径
    chart_path = generate_group_graph(df)
    print("图表已保存到:", chart_path)
